<template>
    <!-- 搜索框 -->
    <div class="search">
        <el-select v-model="searchText" filterable remote reserve-keyword placeholder="输入要查找的信息" loading-text="加载中..."
            no-match-text="无匹配数据" no-data-text="无数据" clearable default-first-option :remote-method="searchResult"
            :loading="loading" @focus="searchdel" @change="searchChange">
            <el-option v-for="item in searchOptions" :key="item._id" :value="item" />
        </el-select>
        <el-button type="primary" @click="add">点击添加</el-button>
    </div>
    <!-- 导出excel -->
    <div class="excel">
        <el-button @click="derive">
            <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-Excel"></use>
            </svg>
            导出excel</el-button>
    </div>
    <!-- 表格数据展示 -->
    <div class="dataTable">
        <el-table :data="tableData" border style="width: 100%" v-loading="tableLoading" element-loading-text="拼命加载中..."
            element-loading-background="rgba(122,122,122,0.5)">
            <el-table-column align="center" label="头像" width="180">
                <template #default="{ $index }">
                    <el-image style="width: 100px; height: 100px" :src="previewImgList[$index]" :zoom-rate="1.2"
                        :preview-src-list="previewImgList" :initial-index="$index" fit="cover" />
                </template>
            </el-table-column>
            <el-table-column align="center" prop="name" label="姓名" width="180" />
            <el-table-column align="center" prop="class" label="班级" />
            <el-table-column align="center" prop="degree" label="学历" />
            <el-table-column align="center" prop="productUrl" label="项目" />
            <el-table-column align="center" prop="cTime" label="创建时间" />
            <el-table-column align="center" label="操作">
                <template #default="{ row }">
                    <el-button type="success" v-has:edit="userAuth" @click="editor(row)">编辑</el-button>
                    <el-button type="primary" v-has:read="userAuth">查看</el-button>
                    <el-button type="danger" v-has:delete="userAuth" @click="delStu(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <s-dialog v-model="dialogFormVisible" :title="dialogTitle" :action="dialogAction" :reviewData="reviewData"
            @ok="dialogAdd"></s-dialog>
    </div>
    <!-- 分页器  -->
    <div class="pagenation">
        <el-pagination background layout="prev, pager, next" :current-page="paramsList.page" :total="total"
            :default-page-size="paramsList.count" @current-change="handlePagination" />
    </div>
</template>
<script setup>
import { ref, onMounted, watch, reactive } from "vue"
// 引入搜索数据的方法
import * as api from "@/api/stu.js"
// 引入store
import useUser from "@/store/users.js"
// 引入dialog
import sDialog from "@/components/sDialog/index.vue"
// 引入element-ui
import { ElMessage, ElMessageBox } from "element-plus"

//使用store
let userStore = useUser()
// console.log(userStore);
// 声明搜索框的值
const searchText = ref([])
// 声明控制搜索loading的变量
const loading = ref(false)
// 声明搜索框的选项
const searchOptions = ref([])
// 声明是不是搜索状态的变量
let Search = false
// 封装搜索的方法
let searchList = async (key = '', isSearch = false, params = {}) => {
    // 搜索状态赋值为true
    Search = true
    isSearch && (tableLoading.value = true)
    // 搜索框的loading
    loading.value = true
    try {
        let res = await api.searchStuApi({ key: key, count: params.count, page: params.page })
        // console.log(res);
        isSearch && (total.value = res.data.total) && (paramsList.page = 1)
        searchOptions.value = Array.from(new Set(res.data.data.map(item => item.name)))
        // console.log(searchOptions.value);
        loading.value = false
        isSearch && (tableData.value = res.data.data) && (tableLoading.value = false)
    } catch (e) {
        console.log(e);
        loading.value = false
        tableLoading.value = false

    }
}
// 声明搜索框的远程搜索方法
let searchResult = (input) => {

    input && searchList(input)
}
// 声明搜索框的聚焦事件 清除搜索框的值
let searchdel = (key) => {
    searchText.value = []
}
// 声明搜索框的change事件
let searchChange = (val) => {
    // 搜索值为空 关闭搜索状态
    if (!val) {
        Search = false
        total.value = 1
        getListStu(paramsList)

    } else {
        paramsList.page = 1
        searchList(val, true, { page: paramsList.page, count: paramsList.count })
    }

}
// 声明控制表格loading的变量
const tableLoading = ref(false)
// 声明获取表格数据的方法
let getListStu = async (params) => {
    // 表格的loading
    tableLoading.value = true
    try {
        let res = await api.getStuListApi(params)
        // console.log(res);
        tableData.value = res.data.data
        // console.log(tableData.value);
        // 对表格的total进行赋值
        total.value = res.data.total
        tableLoading.value = false
    } catch (e) {
        console.log(e);
        tableLoading.value = false
    }
}
// 声明表格数据
const tableData = ref([])
// 声明预览图片的列表
let previewImgList = ref([])
// 监听表格数据的变化，生成预览图片的列表
watch(tableData, (newVal) => {
    previewImgList.value = newVal.map(item => item.headimgurl ? item.headimgurl : 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png')

})
// 声明表格请求数据的参数
const paramsList = reactive({
    page: 1,
    count: 5,
    calss: ''
})
// 声明分页器的总条数
let total = ref(0)
// 声明页码发生变化的处理函数
let handlePagination = (value) => {
    // console.log(value);
    // 是搜索状态
    paramsList.page = value
    if (Search) {
        searchList(searchText.value, true, { page: paramsList.page, count: paramsList.count })
    } else {

        getListStu(paramsList)
    }
}
// 声明导出excel的方法
let derive = () => {
    console.log('导出excel');
}
// 声明变量接收用户权限
let userAuth = userStore.permission
console.log(userAuth.value.buttons);
// 声明自定义指令 实现按钮鉴权
let vHas = {
    mounted(el, binding) {
        // console.log(el);
        // console.log(binding);
        if (binding.value && Array.isArray(binding.value)) {
            if (!binding.arg.includes(binding.value)) {
                el.parentNode.removeChild(el)
            }
        }
    }
}
// 声明title标题
let dialogTitle = ref('')
// 声明dialog的模式
let dialogAction = ref()
// 声明控制dailog显示与隐藏的变量
let dialogFormVisible = ref(false)
// 声明点击添加触发的方法
let add = () => {
    dialogFormVisible.value = true
    dialogTitle.value = '添加学员信息'
    dialogAction.value = 'add'
}
// 声明数据回显的变量
let reviewData = ref()
// 声明点击编辑触发的逻辑
let editor = (row) => {
    dialogFormVisible.value = true
    dialogTitle.value = '编辑学员信息'
    dialogAction.value = 'editor'
    reviewData.value = { ...row }
}
// 声明子组件触发的方法
let dialogAdd = async (input) => {
    console.log(input);
    // 调用添加的方法
    try {
        if (dialogAction.value === 'add') {
            await api.addStuApi(input)
            ElMessage({
                type: 'success',
                message: '添加成功'
            })
        }else if(dialogAction.value === 'editor'){
            await api.editStuApi(input)
            ElMessage({
                type: 'success',
                message: '修改成功'
            })
        }
        getListStu(paramsList)
    } catch (e) {
        console.log(e);
    }
}
// 点击删除触发的逻辑
let delStu = async (row) => {
    ElMessageBox.confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        api.delStuApi(row.sId)
        getListStu(paramsList)
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });

}

// 组件挂载之后调用
onMounted(() => {
    getListStu(paramsList)
})

</script>

<style scoped>
.search .el-select :deep(.el-input__wrapper) {
    width: 200px;
}
</style>